package com.wx.springboot.step9back.service.impl;

import com.wx.springboot.step9back.common.util.MyDate;
import com.wx.springboot.step9back.mapper.WordMapper;
import com.wx.springboot.step9back.model.Collect;
import com.wx.springboot.step9back.model.Like;
import com.wx.springboot.step9back.model.User;
import com.wx.springboot.step9back.model.Word;
import com.wx.springboot.step9back.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("wordService")
public class WordServiceImpl implements WordService {

    @Autowired
    private WordMapper wordMapper;

    @Override
    public List<Word> getSelectList(Map<String, Object> data) {
        int page = Integer.parseInt((String) data.get("pageNum"));
        int size = Integer.parseInt((String)data.get("pageSize"));
        data.put("pageNum",(page-1)*size);
        data.put("pageSize",size);
        return wordMapper.getSelectList(data);
    }

    @Override
    public int getSelectCount(Map<String, Object> data) {
        return wordMapper.getSelectCount(data);
    }

    @Override
    public String addWord(Word word) {
        word.setCreateTime(MyDate.getDate());
        int result = wordMapper.addWord(word);
        if (result > 0) {
            return "success";
        }else {
            return "false";
        }
    }

    @Override
    public Like getLikeByData(Map<String, Object> data) {
        return wordMapper.getLikeByData(data);
    }

    @Override
    public String addLike(Like like) {
        like.setCreateTime(MyDate.getDate());
        int result = wordMapper.addLike(like);
        if (result > 0) {
            changeLikeCount(like.getWordId(),like.getStateCode());
            return "success";
        }else {
            return "false";
        }
    }

    @Override
    public int updateLike(Like like) {
        int result = wordMapper.updateLike(like);
        if (result > 0){
            changeLikeCount(like.getWordId(),like.getStateCode());
        }
        return result;
    }

    private int changeLikeCount(int wordId,String stateCode) {
        int count = wordMapper.getCountByData(wordId,stateCode);
        Map param = new HashMap();
        param.put("likeCount",count);
        param.put("id",wordId);
        return wordMapper.updateLikeCount(param);
    }

    @Override
    public Collect getCollectByData(Map<String, Object> data) {
        return wordMapper.getCollectByData(data);
    }

    @Override
    public String addCollect(Collect collect) {
        collect.setCreateTime(MyDate.getDate());
        int result = wordMapper.addCollect(collect);
        if (result > 0) {
            return "success";
        }else {
            return "false";
        }
    }

    @Override
    public int updateCollect(Collect collect) {
        return wordMapper.updateCollect(collect);
    }

}
